//
//  UIImage_public extension.swift
//  Wanke
//
//  Created by BO ZHOU on 2020/10/26.
//

import UIKit

public extension UIImage {
    
    func compressImage(toByte maxLength: Int) -> UIImage? {
        
        let image = self
        var compression: CGFloat = 1
        
        if var data = image.jpegData(compressionQuality: compression) {
            if data.count > maxLength {
                return image
            } else {
                var max: CGFloat = 1
                var min: CGFloat = 0
                for _ in 0..<6 {
                    compression = (max + min) / 2
                    data = image.jpegData(compressionQuality: compression)!
                    if CGFloat(data.count) < CGFloat(maxLength) * 0.9 {
                        min = compression
                    } else if data.count > maxLength {
                        max = compression
                    } else {
                        break
                    }
                }
                return UIImage(data: data)
            }
        } else {
            return nil
        }
    }
    
    
    func compressImage_data(toByte maxLength: Int) -> Data? {
        
        let image = self
        var compression: CGFloat = 1
        
        if var data = image.jpegData(compressionQuality: compression) {
            if data.count > maxLength {
                return data
            } else {
                var max: CGFloat = 1
                var min: CGFloat = 0
                for _ in 0..<6 {
                    compression = (max + min) / 2
                    data = image.jpegData(compressionQuality: compression)!
                    if CGFloat(data.count) < CGFloat(maxLength) * 0.9 {
                        min = compression
                    } else if data.count > maxLength {
                        max = compression
                    } else {
                        break
                    }
                }
                return data
            }
        } else {
            return nil
        }
    }
    
    
    
    static func named_lib(_ name: String, type: String = "png") -> UIImage? {
        return UIImage(contentsOfFile: libBundlePath + "/\(name)" + "." + "\(type)")
    }
    
    static func named_lib_player(_ name: String, type: String = "png") -> UIImage? {
        return UIImage(contentsOfFile: libPlayerBundlePath + "/\(name)" + "." + "\(type)")
    }
}
